#include<unistd.h>
#include<cassert>
#include<iostream>
#include<error.h>
#include<string.h>
#include<sys/types.h>
#include<sys/wait.h>

using namespace std;

int main()
{
  int pipefd[2];
  int n = pipe(pipefd);
  if(n < 0)
  {
    cout << "pipe fail" << errno << " : " << strerror(errno) << endl;
    return 1;
  }
  else
  {
    cout << "读端: " << pipefd[0] << endl;//0 表示嘴巴，即为读端
    cout << "写端: " << pipefd[1] << endl;//1 表示笔  ，即为写端
  }
  
  pid_t fd = fork();
  assert(fd != -1);
  (void)fd;
  if(fd == 0)//子进程
  {
    close(pipefd[0]);//关闭读端。让子进程只进行写入
    int cnt = 100;
    const char* str = "helllo world";
    while(cnt)
    {
      char Buffer[1024];
      snprintf(Buffer,sizeof(Buffer),"%s %d",str,cnt--);
      write(pipefd[1],Buffer,strlen(Buffer));
      sleep(2);
    }
    close(pipefd[1]);
    exit(0);
  }
  close(pipefd[1]);
  //int cnt = 100;
  while(true)
  {
    char buffer[1024];
    int writen = read(pipefd[0],buffer,sizeof(buffer) - 1);
    if(writen == 0)
    {
      cout << "读到了文件的末尾 , 退出" << endl;
      break;
    }
    else if(writen == -1)
    {
      cout << "read fail " << errno << ": " << strerror(errno) << endl;
      break;
    }
    else
    {
      buffer[writen] = '\0';
      cout << "成功读取到了 " << writen << "个字节,内容为: " << buffer << endl;
    }
    //sleep(1);
  }
  close(pipefd[0]);
  int status = 0;
  waitpid(fd,&status,0);
  cout << "signal " << (status & 0x7F) << endl;  
  return 0;
}



